﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
using System.ComponentModel;
using CommonTools;
using BaseDll;
using MotionIoLib;
using System.IO;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace ModuleUnit
{
    public class ModuleMgr
    {
        private static object obj = new object();
        private static ModuleMgr moduleMgr;
        public Dictionary<string, ModuleBase> dic_ModuleInfo = new Dictionary<string, ModuleBase>();
        /// <summary>
        /// 获取外设数据管理句柄
        /// </summary>
        /// <returns></returns>
        public static ModuleMgr GetInstance()
        {
            if (moduleMgr == null)
            {
                lock (obj)
                {
                    moduleMgr = new ModuleMgr();
                    return moduleMgr;
                }

            }
            else
                return moduleMgr;
        }
        /// <summary>
        /// 读取外设数据
        /// </summary>
        /// <returns></returns>
        public int Read()
        {
            try
            {
                string currentFile = AppDomain.CurrentDomain.BaseDirectory + @"\config\ModuleData.json";
                if (!File.Exists(currentFile))
                {
                    Save();
                }
                string FileText = File.ReadAllText(currentFile);
                Dictionary<string, ModuleBase> ds = JsonConvert.DeserializeObject<Dictionary<string, ModuleBase>>(FileText);
                foreach (var tem in ds)
                {
                    Type type = Type.GetType(tem.Value.strType);
                    object[] args = new object[] { tem.Value.obj_Config, tem.Key };
                    ModuleBase module = Activator.CreateInstance(type, args) as ModuleBase;
                    string strItemElement = tem.Value.obj_Config.ToString().Trim('\r', '\n');
                    module.strType = tem.Value.strType;
                    dic_ModuleInfo.Add(tem.Key, module);
                    module.Init();
                }
                return 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载模块数据失败，错误信息：{ex.Message}");
                return -1;
            }
        }
        /// <summary>
        /// 保存外设数据
        /// </summary>
        /// <returns></returns>
        public int Save()
        {
            string currentFile = AppDomain.CurrentDomain.BaseDirectory + @"\config\ModuleData.json";
            bool a = AccessJosnSerializer.ObjectToJson(currentFile, dic_ModuleInfo);
            return 0;
        }
        public ModuleBase Function_获取指定模块(string strName)
        {
            if (dic_ModuleInfo.ContainsKey(strName))
                return dic_ModuleInfo[strName];
            else
                return null;
        }
    }
}